package com.sy.olddriver.dao.impl;

import com.sy.olddriver.constant.AppConstant;
import com.sy.olddriver.dao.ProductDao;
import com.sy.olddriver.entity.Product;
import com.sy.olddriver.utils.JdbcHelper;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ProductDao接口对应的实现类
 *
 * @author Administrator
 */
public class ProductDaoImpl implements ProductDao {
    @Override
    public List<Product> getNewestProducts(Long limit) {
        return JdbcHelper.queryForBeanList("select * from product order by created desc limit 0,?", Product.class, limit);
    }

    @Override
    public List<Product> getHotestProducts(Long limit) {
        return JdbcHelper.queryForBeanList("select * from product order by clickcount desc limit 0,?", Product.class, limit);
    }

    @Override
    public Long getProductsCountByCondition(String cid, String q) {
        StringBuilder sql = new StringBuilder("select count(*) from product where 1=1 ");
        List<Object> params = new ArrayList<>();
        if (StringUtils.isNotBlank(cid)) {
            sql.append(" and cid=? ");
            params.add(cid);
        }
        if (StringUtils.isNotBlank(q)) {
            sql.append(" and title like CONCAT('%',?,'%') ");
            params.add(q);
        }
        System.out.println("查询数量的SQL:" + sql);
        return JdbcHelper.queryForScalar(sql.toString(), params.toArray());
    }

    @Override
    public List<Product> getProductsByCondition(String cid, String q, Integer start) {
        StringBuilder sql = new StringBuilder("select * from product where 1=1 ");
        List<Object> params = new ArrayList<>();
        if (StringUtils.isNotBlank(cid)) {
            sql.append(" and cid=? ");
            params.add(cid);
        }
        if (StringUtils.isNotBlank(q)) {
            sql.append(" and title like CONCAT('%',?,'%') ");
            params.add(q);
        }
        sql.append(" limit ?,? ");
        params.add(start);
        params.add(AppConstant.SEARCH_RESULT_PAGE_SIZE);
        System.out.println("查询分页数据的SQL:" + sql);
        return JdbcHelper.queryForBeanList(sql.toString(), Product.class, params.toArray());
    }

    @Override
    public Product getProductById(String pid) {
        return JdbcHelper.queryForBean("select * from product where id=?", Product.class, pid);
    }

    @Override
    public boolean addClickCount(String pid) {
        return JdbcHelper.update("update product set clickcount=clickcount+1 where id=?", pid);
    }

    @Override
    public List<Product> getProductsByIds(List<String> ids) {
        String idStr = StringUtils.join(ids.iterator(), AppConstant.COMMA_SEPARATOR);
        String sql = "select * from product where id in (" + idStr + ") ORDER BY FIELD(id," + idStr + ")";
        return JdbcHelper.queryForBeanList(sql, Product.class);
    }

}
